package com.xinfu.newproject.base;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment {
    private View mContentView;
    private Context mContext;
    private Unbinder unbinder;
    private RxPermissions rxPermissions;
    protected String TAG = this.getClass().getSimpleName();
    protected int REQUEST_CODE_ASK_PERMISSION = 0x00099;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContentView = inflater.inflate(setLayoutResourceID(), container, false);
        mContext = getContext();
        rxPermissions = new RxPermissions(getActivity());
        unbinder = ButterKnife.bind(this,mContentView);
        init();
        setUpView();
        setUpData();
        return mContentView;
    }

    /**
     * 此方法用于返回Fragment设置ContentView的布局文件资源ID * * @return 布局文件资源ID
     */
    protected abstract int setLayoutResourceID();

    /**
     * 一些View的相关操作
     */
    protected abstract void setUpView();

    /**
     * 一些Data的相关操作
     */
    protected abstract void setUpData();

    /**
     * 此方法用于初始化成员变量及获取Intent传递过来的数据 * 注意：这个方法中不能调用所有的View，因为View还没有被初始化，要使用View在initView方法中调用
     */
    protected void init() {
    }

    public View getContentView() {
        return mContentView;
    }

    public Context getMContext() {
        return mContext;
    }

    public RxPermissions mRxPermissions() {
        return rxPermissions;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    /**
     * 打开相机或者相册
     */
    public void onClickCamera() {
//        //文本
//        ArrayList<String> listContent = new ArrayList<String>();
//        listContent.add("拍照");
//        listContent.add("从相册选择");
//
//        //文本颜色
//        ArrayList<String> listColor = new ArrayList<String>();
//        listColor.add("#848484");
//        listColor.add("#d50201");
//
//        //文本字体大小
//        ArrayList<String> listContentSize = new ArrayList<String>();
//        listContentSize.add("20");
//        listContentSize.add("18");
//
//        Bundle bundle = new Bundle();
//        bundle.putBoolean(ItemDialogFragment.DIALOG_BACK, true);
//        bundle.putBoolean(ItemDialogFragment.DIALOG_CANCELABLE, true);
//        bundle.putBoolean(ItemDialogFragment.DIALOG_CANCELABLE_TOUCH_OUT_SIDE, true);
//        bundle.putStringArrayList(ItemDialogFragment.DIALOG_ITEM_CONTENT, listContent);
//        bundle.putStringArrayList(ItemDialogFragment.DIALOG_ITEM_COLOR, listColor);
//        bundle.putStringArrayList(ItemDialogFragment.DIALOG_ITEM_CONTENT_SIZE, listContentSize);
//        bundle.putString(ItemDialogFragment.DIALOG_CANCEL, "取消");
//        final ItemDialogFragment dialogFragment = ItemDialogFragment.newInstance(ItemDialogFragment.class, bundle);
//        dialogFragment.setOnItemClickDialogListener(new ItemDialogFragment.OnItemClickDialogListener() {
//            @Override
//            public void onItemClick(int position, String content) {
//                if (position == 0) {//拍照
//                    pictureForCamera();
//                } else if (position == 1) {//从相册选择
//                    pictureForVanGogh();
//                }
//                dialogFragment.dismiss();
//            }
//
//            @Override
//            public void onCancel(TextView tvCancel) {
//                dialogFragment.dismiss();
//            }
//        });
//        dialogFragment.show(getActivity().getSupportFragmentManager(), "");
        pictureForVanGogh();
    }

    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    public void requestPermission(String[] permissions, int requestCode) {
        this.REQUEST_CODE_ASK_PERMISSION = requestCode;
        if (checkPermissions(permissions)) {
            permissionGrant(true, REQUEST_CODE_ASK_PERMISSION);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(getActivity(), needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_ASK_PERMISSION);
        }
    }

    //=====================================================核心代码===================================================================================================================
    private void pictureForCamera() {//拍照
        requestPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0x0001);
    }

    private void pictureForVanGogh() {//从相册选择
        requestPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0x0002);
    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    private boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getMContext(), permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }

    /**
     * 系统请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_ASK_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionGrant(true, REQUEST_CODE_ASK_PERMISSION);
            } else {
                permissionGrant(false, REQUEST_CODE_ASK_PERMISSION);
                showTipsDialog();
            }
        }
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(getMContext())
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行授权。")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        startAppSettings();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
    }

    /**
     * 获取权限是否成功
     *
     * @param isGranted   true:成功权限成功 false:获取权限失败
     * @param requestCode 权限请求码
     */
    @CallSuper
    public void permissionGrant(boolean isGranted, int requestCode) {
        Log.i(TAG, "获取权限是否成功——>" + "isGranted：" + isGranted + " requestCode：" + requestCode);
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
        startActivity(intent);
    }

}
